package com.cicadamob.contact.api.service;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.Context;
import android.os.AsyncTask;

import com.cicadamob.contact.api.Utils.ContactConfig;
import com.cicadamob.contact.api.Utils.StringUtil;
import com.cicadamob.contact.api.Utils.Endecryption.EndecryptionUtil;

public class DownLoadContactAsyTask extends
		AsyncTask<Object, Void, BaseResultModel<Integer>> {

	protected Context context;
	private ICallBack callBack;

	public DownLoadContactAsyTask(Context context,ICallBack callBack) {
		this.context = context;
		this.callBack=callBack;
	}

	@Override
	protected BaseResultModel<Integer> doInBackground(Object... params) {
		// TODO Auto-generated method stub

		String encdata = ContactConfig.getMobile(context) + ";"
				+ ContactConfig.getIMSI(context) + ";" + ContactConfig.getIMEI(context)
				+ ";" + StringUtil.getRandomStr(7) + ";"
				+ StringUtil.getStrDate(new Date(), "yyyy-MM-dd hh:mm:ss");
		String des = EndecryptionUtil.encode3DesAndBase64(encdata,
				ContactHttpClient.KEY);
		String dd = StringUtil.encode(des);
		// String
		// fileName=Environment.getExternalStorageDirectory().getAbsolutePath()+"/ManagerAssistant/download/";
		String mobile = ContactConfig.getMobile(context);
		String imsi = ContactConfig.getIMSI(context);
		String imei = ContactConfig.getIMEI(context);
		String version = "0";
		String authentication = dd;
		String Connection = "close";
		Map<String, String> requestParam = new HashMap<String, String>();
		requestParam.put("mobile", mobile);
		requestParam.put("imsi", imsi);
		requestParam.put("imei", imei);
		requestParam.put("version", version);
		requestParam.put("authentication", authentication);
		requestParam.put("Connection", Connection);

		String url = ServerUrl.COMPANY_DB3_URL+"?fromid="+ContactConfig.getMobile(context)+"&mobile="+ContactConfig.getCompanyValidMobile(context)+"&vcode="+ContactConfig.getCompanyValidVCode(context)+"&companyId="+ContactConfig.getCompanyValidCompanyId(context);
		
		int status = ContactHttpClient.downloadFile(url, requestParam,
				DownloadUtils.DOWNLOAD_PATH, ContactDbHelper.DBFILE);

		if (status == ContactHttpClient.CODE_OK) {
			// 拷贝文件至内存中，并删除SD卡上的文件。
			try {
				String path = DownloadUtils.DOWNLOAD_PATH
						+ ContactDbHelper.DBFILE;
				boolean canOpen = ContactDbHelper.canOpen(path);// 打开数据库
				if (canOpen) {
					boolean suc = loadingContactDbToRam(context);// 将数据库拷贝到内存，并删除下载在sd卡上的文件
					ContactDbHelper.reloadDataBase();
					if (suc) {
						// 生成同事组织路径
						ContactDbHelper.getInstance().createComPanyTreePath();
					}
					if (downloadClientDB()) {
						// 生成客户组织路径
						ContactDbHelper.getInstance().createClientTreePath();
					}
					return new BaseResultModel<Integer>(0, "通讯录下载成功", Integer.valueOf(status));
				}
			} catch (Exception e) {
				e.printStackTrace();
				return new BaseResultModel<Integer>(-1, "通讯录下载失败", Integer.valueOf(status));
			}
		} else if (status == ContactHttpClient.CODE_CONFLICT) {
			return new BaseResultModel<Integer>(-1, "通讯录下载失败  原因：已有用户，冲突", Integer.valueOf(status));
		} else {
			
			return new BaseResultModel<Integer>(-1, "通讯录下载失败 错误码："+status, Integer.valueOf(status));
		}

		return null;
	}

	@Override
	protected void onPostExecute(BaseResultModel<Integer> result) {
		// TODO Auto-generated method stub
		if(this.callBack!=null) callBack.respone(result);
		super.onPostExecute(result);
		
		StringBuilder sb=new StringBuilder();
		sb.append("方法：downLoadContact(),action：返回，返回数据：rCode="+result.getrCode());
		WriteLog.WriteLocationListLogSDK(sb.toString());
	}

	/**
	 * 加载客户数据文件
	 * 
	 * @return
	 */
	private boolean downloadClientDB() {
		String encdata = ContactConfig.getMobile(context) + ";"
				+ ContactConfig.getIMSI(context) + ";" + ContactConfig.getIMEI(context)
				+ ";" + StringUtil.getRandomStr(7) + ";"
				+ StringUtil.getStrDate(new Date(), "yyyy-MM-dd hh:mm:ss");
		String des = EndecryptionUtil.encode3DesAndBase64(encdata,
				ContactHttpClient.KEY);
		String dd = StringUtil.encode(des);

		String mobile = ContactConfig.getMobile(context);
		String imsi = ContactConfig.getIMSI(context);
		String imei = ContactConfig.getIMEI(context);
		String version = "0";
		String authentication = dd;
		String Connection = "close";
		Map<String, String> requestParam = new HashMap<String, String>();
		requestParam.put("mobile", mobile);
		requestParam.put("imsi", imsi);
		requestParam.put("imei", imei);
		requestParam.put("version", version);
		requestParam.put("authentication", authentication);
		requestParam.put("Connection", Connection);

		String url = StringUtil.getBuffer().append(ServerUrl.CLIENT_DATA_URL)
				.append("?mobile=" + mobile).toString();

		String fileName = mobile + "_clientdata.txt";
		// 下载需要更新文件
		int status = ContactHttpClient.downloadFile(url, requestParam,
				DownloadUtils.DOWNLOAD_PATH, fileName);
		if (status == 200) {
			try {
				parseJsonFile(fileName);
			} catch (ServerException e) {
				/** 2013-7-19下午3:35:51 请别忘记对异常进行处理 Administrator ServerException */
				e.printStackTrace();
				return false;
			}
		}
		return true;
	}

	/**
	 * 解析下载下来的需要更新的json文件
	 * 
	 * @param filename
	 * @return
	 * @throws ServerException
	 */
	private void parseJsonFile(String filename) throws ServerException {
		File file = new File(DownloadUtils.DOWNLOAD_PATH + filename);
		BufferedReader br = null;
		FileInputStream fis = null;
		List<String> sqlList = new ArrayList<String>();
		try {
			fis = new FileInputStream(file);
			br = new BufferedReader(new InputStreamReader(fis));
			String sqlValue = null;
			// miaozz add 因为客户表可添加多个公司节点为-1，故在上层再添加一个节点为-2
			// if(Const.CRMASSISTANT == ServerUrl.ProjectNO) {
			// ContactDbHelper.getInstance().insert2ClientTree();
			// }

			while ((sqlValue = br.readLine()) != null) {
				sqlList.add(sqlValue);
				// ContactDbHelper.getInstance().executeSQL(sqlValue);
			}
			ContactDbHelper.getInstance().executesql(sqlList);
		} catch (FileNotFoundException e) {
			/**
			 * 2013-7-19下午6:22:16 请别忘记对异常进行处理 Administrator
			 * FileNotFoundException
			 */
			e.printStackTrace();
		} catch (IOException e) {
			/**
			 * 2013-7-19下午6:24:48 请别忘记对异常进行处理 Administrator IOException
			 */
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (br != null) {
					br.close();
				}

				if (fis != null) {
					fis.close();
				}
			} catch (IOException e) {
				/**
				 * 2013-7-19下午6:31:54 请别忘记对异常进行处理 Administrator IOException
				 */
				e.printStackTrace();
			}
			if (file.exists())
				file.delete();
		}
	}

	private boolean loadingContactDbToRam(Context context) {
		// 读取整个文件到内存数据库中
		try {
			FileOutputStream fos = context.openFileOutput(
					ContactDbHelper.DBFILE, 0);
			FileInputStream fis = new FileInputStream(FilePath.DOWNLOAD_PATH
					+ ContactDbHelper.DBFILE);
			byte[] buffer = new byte[1024 * 4];
			int len = 0;
			while ((len = fis.read(buffer)) != -1) {
				fos.write(buffer, 0, len);
			}
			fis.close();
			fos.close();
			File file = new File(FilePath.DOWNLOAD_PATH
					+ ContactDbHelper.DBFILE);
			// 删除sd卡的临时文件
			if (file.exists())
				file.delete();
			file = null;
			fis = null;
			fos = null;
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

}
